<template>
    <div class="weather-trend-chart">
        <h3 class="chart-title">天气趋势分析</h3>

        <!-- 图表类型选择 -->
        <div class="chart-controls">
            <div class="chart-type-selector">
                <label class="chart-type-option">
                    <input type="radio" v-model="selectedChartType" value="temperature" />
                    <span class="option-label">温度趋势</span>
                </label>
                <label class="chart-type-option">
                    <input type="radio" v-model="selectedChartType" value="humidity" />
                    <span class="option-label">湿度趋势</span>
                </label>
                <label class="chart-type-option">
                    <input type="radio" v-model="selectedChartType" value="wind" />
                    <span class="option-label">风速趋势</span>
                </label>
                <label class="chart-type-option">
                    <input type="radio" v-model="selectedChartType" value="precipitation" />
                    <span class="option-label">降水趋势</span>
                </label>
            </div>

            <div class="time-range-selector">
                <label class="time-option">
                    <input type="radio" v-model="selectedTimeRange" value="7" />
                    <span class="option-label">7天</span>
                </label>
                <label class="time-option">
                    <input type="radio" v-model="selectedTimeRange" value="15" />
                    <span class="option-label">15天</span>
                </label>
                <label class="time-option">
                    <input type="radio" v-model="selectedTimeRange" value="30" />
                    <span class="option-label">30天</span>
                </label>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="chart-container">
            <canvas ref="chartCanvas" width="1000" height="500"></canvas>
        </div>

        <!-- 趋势分析 -->
        <div class="trend-analysis">
            <div class="trend-summary">
                <div class="trend-item">
                    <div class="trend-label">整体趋势</div>
                    <div class="trend-value" :class="getOverallTrendClass()">
                        {{ getOverallTrend() }}
                    </div>
                </div>
                <div class="trend-item">
                    <div class="trend-label">变化幅度</div>
                    <div class="trend-value">
                        {{ getChangeAmplitude() }}
                    </div>
                </div>
                <div class="trend-item">
                    <div class="trend-label">预测建议</div>
                    <div class="trend-value">
                        {{ getPredictionAdvice() }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import type { WeatherData } from '@/services/weatherService'

interface Props {
    weatherData: WeatherData[]
    cityName?: string
}

const props = withDefaults(defineProps<Props>(), {
    cityName: '当前城市'
})

const selectedChartType = ref('temperature')
const selectedTimeRange = ref(7)
const chartCanvas = ref<HTMLCanvasElement>()

// 监听图表类型和时间范围变化
watch([selectedChartType, selectedTimeRange], () => {
    nextTick(() => {
        drawChart()
    })
})

// 监听天气数据变化
watch(() => props.weatherData, (newData) => {
    console.log('天气数据变化，重新绘制图表:', newData)
    nextTick(() => {
        drawChart()
    })
}, { deep: true, immediate: true })

onMounted(() => {
    console.log('WeatherTrendChart 组件挂载完成，天气数据:', props.weatherData)
    nextTick(() => {
        drawChart()
    })
})

// 绘制图表
const drawChart = () => {
    if (!chartCanvas.value) return

    const ctx = chartCanvas.value.getContext('2d')
    if (!ctx) return

    const canvas = chartCanvas.value
    const width = canvas.width
    const height = canvas.height

    // 清空画布
    ctx.clearRect(0, 0, width, height)

    // 绘制背景
    ctx.fillStyle = '#f8f9fa'
    ctx.fillRect(0, 0, width, height)

    // 绘制网格
    drawGrid(ctx, width, height)

    // 绘制数据
    drawData(ctx, width, height)

    // 绘制坐标轴标签
    drawLabels(ctx, width, height)
}

// 绘制网格
const drawGrid = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
    ctx.strokeStyle = '#e9ecef'
    ctx.lineWidth = 1

    // 垂直线
    const days = parseInt(selectedTimeRange.value.toString())
    for (let i = 0; i <= days; i++) {
        const x = (i / days) * width
        ctx.beginPath()
        ctx.moveTo(x, 0)
        ctx.lineTo(x, height - 60)
        ctx.stroke()
    }

    // 水平线
    const lines = 8
    for (let i = 0; i <= lines; i++) {
        const y = (i / lines) * (height - 60)
        ctx.beginPath()
        ctx.moveTo(0, y)
        ctx.lineTo(width, y)
        ctx.stroke()
    }
}

// 绘制数据
const drawData = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
    console.log('开始绘制图表数据，天气数据长度:', props.weatherData.length)

    const days = parseInt(selectedTimeRange.value.toString())
    const data = getChartData()

    console.log('生成的图表数据:', data)

    if (data.length === 0) {
        console.log('图表数据为空，无法绘制')
        return
    }

    // 绘制曲线
    ctx.strokeStyle = getChartColor()
    ctx.lineWidth = 3
    ctx.beginPath()

    data.forEach((value, index) => {
        const x = (index / (data.length - 1)) * width
        const y = height - 60 - (value / getMaxValue()) * (height - 60)

        if (index === 0) {
            ctx.moveTo(x, y)
        } else {
            ctx.lineTo(x, y)
        }

        // 绘制数据点
        ctx.fillStyle = getChartColor()
        ctx.beginPath()
        ctx.arc(x, y, 5, 0, 2 * Math.PI)
        ctx.fill()
    })

    ctx.stroke()
}

// 绘制坐标轴标签
const drawLabels = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
    ctx.fillStyle = '#333'
    ctx.font = '12px Arial'
    ctx.textAlign = 'center'

    // X轴标签（日期）
    const days = parseInt(selectedTimeRange.value.toString())
    for (let i = 0; i <= days; i++) {
        const x = (i / days) * width
        const date = new Date()
        date.setDate(date.getDate() + i)
        const label = date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
        ctx.fillText(label, x, height - 20)
    }

    // Y轴标签
    const maxValue = getMaxValue()
    const lines = 8
    for (let i = 0; i <= lines; i++) {
        const y = (i / lines) * (height - 60)
        const value = (maxValue - (i / lines) * maxValue).toFixed(1)
        ctx.textAlign = 'right'
        ctx.fillText(value, 50, y + 4)
    }
}

// 获取图表数据
const getChartData = () => {
    const data: number[] = []
    const days = parseInt(selectedTimeRange.value.toString())

    for (let i = 0; i < days; i++) {
        const date = new Date()
        date.setDate(date.getDate() + i)

        let value = 0
        switch (selectedChartType.value) {
            case 'temperature':
                value = 20 + Math.sin(i * 0.5) * 10 + Math.random() * 5
                break
            case 'humidity':
                value = 60 + Math.cos(i * 0.3) * 20 + Math.random() * 10
                break
            case 'wind':
                value = 5 + Math.sin(i * 0.7) * 3 + Math.random() * 2
                break
            case 'precipitation':
                value = Math.random() * 100
                break
        }

        data.push(Math.max(0, value))
    }

    return data
}

// 获取最大值
const getMaxValue = () => {
    const data = getChartData()
    return Math.max(...data) * 1.2
}

// 获取图表颜色
const getChartColor = () => {
    const colors = {
        temperature: '#e74c3c',
        humidity: '#3498db',
        wind: '#f39c12',
        precipitation: '#9b59b6'
    }
    return colors[selectedChartType.value as keyof typeof colors] || '#333'
}

// 趋势分析
const getOverallTrend = () => {
    const data = getChartData()
    if (data.length < 2) return '数据不足'

    const firstHalf = data.slice(0, Math.floor(data.length / 2))
    const secondHalf = data.slice(Math.floor(data.length / 2))

    const firstAvg = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length
    const secondAvg = secondHalf.reduce((a, b) => a + b, 0) / secondHalf.length

    if (secondAvg > firstAvg * 1.1) return '↗️ 上升趋势'
    if (secondAvg < firstAvg * 0.9) return '↘️ 下降趋势'
    return '→ 相对稳定'
}

const getOverallTrendClass = () => {
    const trend = getOverallTrend()
    if (trend.includes('上升')) return 'trend-up'
    if (trend.includes('下降')) return 'trend-down'
    return 'trend-stable'
}

const getChangeAmplitude = () => {
    const data = getChartData()
    if (data.length === 0) return '--'

    const max = Math.max(...data)
    const min = Math.min(...data)
    const amplitude = max - min

    if (amplitude < 5) return '变化很小'
    if (amplitude < 15) return '变化较小'
    if (amplitude < 30) return '变化中等'
    return '变化较大'
}

const getPredictionAdvice = () => {
    const trend = getOverallTrend()
    const chartType = selectedChartType.value

    if (trend.includes('上升')) {
        switch (chartType) {
            case 'temperature': return '温度将持续升高，注意防暑降温'
            case 'humidity': return '湿度将增加，注意防潮'
            case 'wind': return '风力将增强，注意防风'
            case 'precipitation': return '降水概率增加，注意防雨'
        }
    } else if (trend.includes('下降')) {
        switch (chartType) {
            case 'temperature': return '温度将持续下降，注意保暖'
            case 'humidity': return '湿度将减少，注意保湿'
            case 'wind': return '风力将减弱，适合户外活动'
            case 'precipitation': return '降水概率减少，天气转好'
        }
    } else {
        return '天气相对稳定，可正常安排活动'
    }

    return '建议关注天气变化'
}
</script>

<style scoped>
.weather-trend-chart {
    background: white;
    border-radius: 20px;
    padding: 35px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    border: 1px solid #e9ecef;
    margin-bottom: 30px;
}

.chart-title {
    font-size: 1.8rem;
    margin-bottom: 30px;
    color: #2c3e50;
    text-align: center;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    letter-spacing: 1px;
}

.chart-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 25px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #dee2e6;
}

.chart-type-selector,
.time-range-selector {
    display: flex;
    gap: 15px;
}

.chart-type-option,
.time-option {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
}

.option-label {
    font-size: 15px;
    color: #2c3e50;
    font-weight: 500;
    cursor: pointer;
    transition: color 0.3s ease;
}

.option-label:hover {
    color: #007bff;
}

.chart-container {
    text-align: center;
    margin-bottom: 25px;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chart-container canvas {
    border: 2px solid #e9ecef;
    border-radius: 12px;
    max-width: 100%;
    height: auto;
    background: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.trend-analysis {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #dee2e6;
}

.trend-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
}

.trend-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border: 1px solid #e9ecef;
    transition: all 0.3s ease;
}

.trend-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.trend-label {
    font-weight: 600;
    color: #2c3e50;
    font-size: 1.1rem;
}

.trend-value {
    font-weight: 700;
    font-size: 1.2rem;
    color: #007bff;
}

.trend-up {
    color: #28a745;
}

.trend-down {
    color: #dc3545;
}

.trend-stable {
    color: #6c757d;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .weather-trend-chart {
        padding: 20px;
    }

    .chart-controls {
        flex-direction: column;
        gap: 20px;
    }

    .chart-type-selector,
    .time-range-selector {
        justify-content: center;
    }

    .trend-summary {
        grid-template-columns: 1fr;
    }
}
</style>